package edu.biwu.config;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;
import javax.xml.crypto.Data;

/**
 * @author 王俊彪
 * @version 1.0
 * 这个类作为spring的配置类，用来取代spring配置文件
 */
@Configurable//代表这个类是spring配置类，相当于将xml转换成java类和注解形式
@ComponentScan("edu.biwu")//开启注解扫描
@PropertySource("classpath:db.properties")//加载配置文件
public class SpringConfig {
    /*将配置文件中的值注入到相应属性中*/
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.user}")
    private String username;
    @Value("${jdbc.password}")
    private String password;


    /**
     * 用于返回实例的方法上，相当于将方法的返回值定义成一个Bean
     *
     * @return
     */
    @Bean("dataSource")
    public DataSource initDataSource(){
        /*新建数据源，给数据库设置数据库连接信息*/
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(driver);
        basicDataSource.setUrl(url);
        basicDataSource.setUsername(username);
        basicDataSource.setPassword(password);
        return basicDataSource;
    }

    @Bean("queryRunner")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public QueryRunner initQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }
}
